<template>
  <view class="verification-screen">
    <view class="verification-content">
      <text class="verification-title">输入验证码</text>
      <text class="sms-hint"
        >验证码已经发送到
        <text style="color: #000">{{ formattedPhoneNumber }}</text
        >，请稍等</text
      >

      <view class="code-input-section">
        <!-- 显示的验证码框 -->
        <view class="code-inputs" @tap="focusInput">
          <view
            v-for="(item, index) in codeLength"
            :key="index"
            class="code-input-box"
            :class="{ active: verificationCode.length === index && isFocus }"
          >
            {{
              verificationCode.length >= index + 1
                ? verificationCode[index]
                : ""
            }}
          </view>
        </view>

        <!-- 隐藏的真实输入框 -->
        <input
          v-if="isFocus"
          type="number"
          class="hidden-input"
          v-model="verificationCode"
          :maxlength="codeLength"
          :focus="true"
          @input="handleInput"
          @blur="handleBlur"
        />
      </view>

      <view class="resend-section">
        <text
          class="resend-btn"
          :class="{ disabled: countdown > 0 }"
          @click="resendCode"
        >
          <template v-if="countdown > 0">
            <text class="countdown-number">{{ countdown }}秒</text
            >后重新获取验证码
          </template>
          <template v-else> 重新获取验证码 </template>
        </text>
      </view>
    </view>
  </view>
</template>

<script>
import { authApi } from "@/request/api.js";
import authManager from "@/utils/auth.js";
import cartManager from '@/utils/cart.js'

export default {
  data() {
    return {
      phoneNumber: "",
      countryCode: "+86",
      verificationCode: "",
      codeLength: 6,
      isFocus: false,
      countdown: 0,
      countdownTimer: null,
    };
  },

  computed: {
    formattedPhoneNumber() {
      const phone = this.phoneNumber;
      if (phone.length >= 7) {
        return (
          phone.slice(0, 3) + " " + phone.slice(3, 7) + " " + phone.slice(7)
        );
      }
      return phone;
    },
  },

  onLoad(options) {
    // 从上一页面接收手机号参数
    if (options.phoneNumber) {
      this.phoneNumber = options.phoneNumber;
    }
    if (options.countryCode) {
      this.countryCode = options.countryCode;
    }
      this.startCountdown();
  },

  //   onShow() {
  //     this.startCountdown();
  //   },

  onUnload() {
    // 页面卸载时清除定时器
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }
  },

  methods: {
    // 返回上一步
    goBack() {
      uni.navigateBack();
    },

    // 开始倒计时
    startCountdown() {
      this.countdown = 60;
      this.countdownTimer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(this.countdownTimer);
        }
      }, 1000);
    },

    // 重新发送验证码
    async resendCode() {
      if (this.countdown > 0) return;

      try {
        uni.showLoading({
          title: "发送中...",
        });

        // 调用2506销售端发送短信验证码接口
        const smsData = {
          mobile: this.phoneNumber,
          verifyType: 101,
        };

        await authApi.sendSmsCode(smsData);

        uni.hideLoading();
        uni.showToast({
          title: "验证码已发送",
          icon: "success",
        });

        this.startCountdown();
      } catch (error) {
        uni.hideLoading();
        console.error("重新发送验证码失败:", error);
        uni.showToast({
          title: error.message || "发送验证码失败，请重试",
          icon: "none",
        });
      }
    },

    // 点击显示框聚焦输入
    focusInput() {
      this.isFocus = true;
    },

    // 处理输入
    handleInput(event) {
      const value = event.detail.value;
      console.log("输入验证码:", value);

      // 只保留数字
      this.verificationCode = value.replace(/[^\d]/g, "");

      // 检查是否输入完成
      if (this.verificationCode.length === this.codeLength) {
        this.isFocus = false;
        setTimeout(() => {
          this.verifyCode();
        }, 300);
      }
    },

    // 输入框失焦
    handleBlur() {
      this.isFocus = false;
    },
    // 获取微信登录code
    getWechatLoginCode() {
      return new Promise((resolve, reject) => {
        uni.login({
          provider: "weixin",
          success: (res) => {
            if (res.code) {
              resolve(res.code);
            } else {
              reject(new Error('获取微信登录code失败'));
            }
          },
          fail: (err) => {
            console.error("微信登录失败:", err);
            reject(new Error('微信登录失败'));
          },
        });
      });
    },
    // 验证验证码
    async verifyCode() {
      try {
        uni.showLoading({
          title: "验证中...",
        });

        const loginCode = await this.getWechatLoginCode()

        // 调用2506销售端验证码验证接口
        const verifyData = {
          mobile: this.phoneNumber,
          smsCode: this.verificationCode,
          loginCode
        };

        const result = await authApi.phoneLogin(verifyData);

        // 使用auth管理工具保存登录信息
        authManager.saveLoginInfo(result);

        // 登录成功
        this.loginSuccess();
      } catch (error) {
        console.error("验证码验证失败:", error);
        uni.showToast({
          title: error.message || "验证码错误",
          icon: "none",
        });
        this.clearCode();
      } finally {
        uni.hideLoading();
      }
    },

    // 清空验证码
    clearCode() {
      this.verificationCode = "";
      this.isFocus = true;
    },

    // 登录成功
    async loginSuccess() {
      uni.showToast({
        title: "登录成功",
        icon: "success",
      });
      await cartManager.onUserLogin()
      // 跳转到主页
      setTimeout(() => {
        uni.switchTab({
          url: "/pages/index/index",
        });
      }, 1500);
    },
  },
};
</script>

<style scoped lang="scss">
/* 验证码输入页样式 */
.verification-screen {
  width: 100%;
  height: 100%;
  background: white;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 32rpx;
  border-bottom: 2rpx solid #e5e5e5;
}

.back-btn {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 48rpx;
  color: #666;
}

.header-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.header-right {
  display: flex;
  gap: 32rpx;
}

.menu-btn,
.close-btn {
  font-size: 40rpx;
  color: #666;
}

.verification-content {
  flex: 1;
  padding: 80rpx 40rpx;
  text-align: center;
}

.verification-title {
  font-size: 45rpx;
  font-weight: 500;
  color: #000;
  display: block;
  margin-bottom: 62rpx;
}

.sms-hint {
  color: #999;
  font-size: 28rpx;
  display: block;
  margin-bottom: 80rpx;
}

.code-input-section {
  margin-bottom: 80rpx;
  position: relative;
}

.code-inputs {
  display: flex;
  justify-content: center;
  gap: 24rpx;
}

.code-input-box {
  width: 100rpx;
  height: 100rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  font-weight: bold;
  background: #f8f9fa;
  color: #333;
}

.code-input-box.active {
  border-color: #715091;
  background: white;
}

.hidden-input {
  position: absolute;
  top: -9999rpx;
  left: -9999rpx;
  width: 0;
  height: 0;
  opacity: 0;
}

.resend-section {
  margin-bottom: 80rpx;
}

.resend-btn {
  color: #715091;
  font-size: 28rpx;
}

.resend-btn.disabled {
  color: #999;
}

.countdown-number {
  color: black;
}
</style>
